package cn.edu.ctbu.demo1.api;


import cn.edu.ctbu.demo1.core.PageUtils;
import cn.edu.ctbu.demo1.domain.Student;
import cn.edu.ctbu.demo1.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/student")
@Slf4j
public class StudentApiController {

    @Autowired
    private StudentService studentService;


    /**
     * 读取的url:/api/student/list
     *
     * @return
     */

    @GetMapping("/list")
    public List<Student> findByNameLike(String name) {
        List<Student> students = null;
        if (name == null || name.equals(""))
            students = studentService.findAll();
        else
            students = studentService.findByNameLike("%" + name + "%");
        return students;
    }

    /**
     * 读取的url:/api/student/get/id
     *
     * @return
     */

    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id) {
        Student student = studentService.getById(id);

        return student;
    }

    /**
     * 新增学生的方法./api/student/insert
     * @param student
     */
    @PostMapping("/insert")
    public void insert(@Valid Student student, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            String errStr = bindingResult.getFieldError().getDefaultMessage();
            log.error(errStr);
        }
        studentService.Insert(student);

        log.info(student.toString());
    }


    /**
     * 更新学生的方法./api/student/update
     * @param student
     */
    @PutMapping ("/update")
    public void update(Student student){

        studentService.update(student);

        log.info(student.toString());
    }

    /**
     * 删除学生的方法./api/student/delete
     * @param id
     */
    @DeleteMapping ("/delete/{id}")
    public void delete(@PathVariable Integer id){

        studentService.delete(id);

//        log.info(student.toString());
    }

    /**
     *
     * 分页读取全部内容
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils findByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                                @RequestParam(value = "size",defaultValue = "10")Integer size,
                                @RequestParam(value = "name",defaultValue = "")String name,
                                @RequestParam(value = "sex",defaultValue = "")String sex,
                                @RequestParam(value = "classname",defaultValue = "")String classname,
                                @RequestParam(value = "score",defaultValue = "")String score,
                                @RequestParam(value = "age",defaultValue = "")String age
                               ){

        Page<Student> studentPage ;
        if(StringUtils.isEmpty(name) && StringUtils.isEmpty(classname) && StringUtils.isEmpty(age)
        && StringUtils.isEmpty(sex) && StringUtils.isEmpty(score)
        ){
            Pageable pageable = PageRequest.of(page,size, Sort.by("id"));
            studentPage =studentService.findAll(pageable);
        }else {
            Student student = new Student();
            student.setName(name);
            student.setSex(sex);
            student.setClassname(classname);
            try {
                student.setAge(Integer.valueOf(age));
            } catch (Exception e){}
            try {
                student.setScore(Integer.valueOf(score));
            } catch (Exception e){}

            Pageable pageable = PageRequest.of(page,size,Sort.by("id"));
            ExampleMatcher matcher =ExampleMatcher.matching()
                    .withMatcher("age",ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("score",ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("classname",ExampleMatcher.GenericPropertyMatchers.contains());

            Example<Student> example = Example.of(student,matcher);
//        Example<Student> example = Example.of(student);
            studentPage = studentService.findAll(example,pageable);
        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }
}
